import Vue from 'vue'
import Vuex from 'vuex'
import plants from './modules/plants'

Vue.use(Vuex)

// 模拟数据
const mockPlants = [
  {
    id: 1,
    name: '银杏',
    scientificName: 'Ginkgo biloba',
    category: '乔木',
    distribution: '中国、日本、韩国',
    morphology: '银杏为落叶大乔木，胸径可达4米，树皮灰褐色...',
    ecological: '适应性强，喜光，较耐寒...',
    economicValue: '木材可用于家具制作，种子可食用...',
    medicinalValue: '叶片含银杏内酯，具有改善脑循环作用...',
    components: [
      { name: '银杏内酯A', content: '0.3-0.5', structure: 'C20H24O9' },
      { name: '银杏内酯B', content: '0.2-0.4', structure: 'C20H24O10' }
    ],
    updateTime: '2023-06-15'
  },
  {
    id: 2,
    name: '人参',
    scientificName: 'Panax ginseng',
    category: '草本',
    distribution: '中国东北、朝鲜、俄罗斯',
    morphology: '多年生草本植物，根肉质肥厚...',
    ecological: '喜阴凉湿润环境，耐寒...',
    economicValue: '名贵中药材，具有很高的经济价值...',
    medicinalValue: '具有补气养血、提高免疫力等功效...',
    components: [
      { name: '人参皂苷Rb1', content: '0.8-1.2', structure: 'C54H92O23' },
      { name: '人参皂苷Rg1', content: '0.3-0.5', structure: 'C42H72O14' }
    ],
    updateTime: '2023-06-12'
  }
]

export default new Vuex.Store({
  modules: {
    plants
  },
  state: {
    user: null,
    token: localStorage.getItem('token') || null,
    plants: [],
    components: [],
    statistics: {
      plantCount: 0,
      componentCount: 0,
      achievementCount: 0,
      visitCount: 0
    },
    sidebarOpen: true,
    loading: false,
    error: null
  },
  mutations: {
    SET_USER(state, user) {
      state.user = user
    },
    SET_TOKEN(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    SET_PLANTS(state, plants) {
      state.plants = plants
    },
    SET_COMPONENTS(state, components) {
      state.components = components
    },
    SET_STATISTICS(state, statistics) {
      state.statistics = statistics
    },
    TOGGLE_SIDEBAR(state) {
      state.sidebarOpen = !state.sidebarOpen
    },
    SET_LOADING(state, loading) {
      state.loading = loading
    },
    SET_ERROR(state, error) {
      state.error = error
    }
  },
  actions: {
    login({ commit }, { username, password, remember }) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)
      
      return new Promise((resolve, reject) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            if (!username || !password) {
              throw new Error('用户名和密码不能为空')
            }
            
            if (password.length < 6) {
              throw new Error('密码长度不能少于6位')
            }

            const user = {
              id: 1,
              username,
              role: 'admin',
              avatar: 'https://picsum.photos/200/200'
            }
            const token = 'mock-token-' + Date.now()
            
            commit('SET_USER', user)
            commit('SET_TOKEN', token)
            
            if (remember) {
              localStorage.setItem('remember', 'true')
            }
            
            resolve(user)
          } catch (error) {
            reject(error)
          } finally {
            commit('SET_LOADING', false)
          }
        }, 1000)
      })
    },

    logout({ commit }) {
      commit('SET_USER', null)
      commit('SET_TOKEN', null)
      localStorage.removeItem('remember')
      localStorage.removeItem('token')
    },

    fetchPlants({ commit }) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)

      return new Promise((resolve, reject) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            commit('SET_PLANTS', mockPlants)
            resolve(mockPlants)
          } catch (error) {
            commit('SET_ERROR', error.message)
            reject(error)
          } finally {
            commit('SET_LOADING', false)
          }
        }, 800)
      })
    },

    fetchStatistics({ commit }) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)

      return new Promise((resolve, reject) => {
        // 模拟API调用
        setTimeout(() => {
          try {
            const mockStatistics = {
              plantCount: mockPlants.length,
              componentCount: mockPlants.reduce((sum, plant) => sum + (plant.components?.length || 0), 0),
              achievementCount: 46,
              visitCount: Math.floor(1000 + Math.random() * 500)
            }
            commit('SET_STATISTICS', mockStatistics)
            resolve(mockStatistics)
          } catch (error) {
            commit('SET_ERROR', error.message)
            reject(error)
          } finally {
            commit('SET_LOADING', false)
          }
        }, 600)
      })
    },

    addPlant({ commit, state }, plant) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)

      return new Promise((resolve, reject) => {
        setTimeout(() => {
          try {
            const newPlant = {
              ...plant,
              id: state.plants.length + 1,
              updateTime: new Date().toISOString().split('T')[0]
            }
            const updatedPlants = [...state.plants, newPlant]
            commit('SET_PLANTS', updatedPlants)
            resolve(newPlant)
          } catch (error) {
            commit('SET_ERROR', error.message)
            reject(error)
          } finally {
            commit('SET_LOADING', false)
          }
        }, 1000)
      })
    },

    updatePlant({ commit, state }, { id, plant }) {
      commit('SET_LOADING', true)
      commit('SET_ERROR', null)

      return new Promise((resolve, reject) => {
        setTimeout(() => {
          try {
            const index = state.plants.findIndex(p => p.id === id)
            if (index === -1) {
              throw new Error('植物不存在')
            }

            const updatedPlant = {
              ...state.plants[index],
              ...plant,
              updateTime: new Date().toISOString().split('T')[0]
            }
            const updatedPlants = [...state.plants]
            updatedPlants[index] = updatedPlant
            commit('SET_PLANTS', updatedPlants)
            resolve(updatedPlant)
          } catch (error) {
            commit('SET_ERROR', error.message)
            reject(error)
          } finally {
            commit('SET_LOADING', false)
          }
        }, 1000)
      })
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    currentUser: state => state.user,
    isLoading: state => state.loading,
    error: state => state.error,
    plantCount: state => state.statistics.plantCount,
    componentCount: state => state.statistics.componentCount,
    achievementCount: state => state.statistics.achievementCount,
    visitCount: state => state.statistics.visitCount,
    plantById: state => id => state.plants.find(p => p.id === id)
  }
}) 